﻿using System;
using System.Web;
using System.Web.UI;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace QzEbook.ReWrite
{
    public class RewriterFactoryHandler : IHttpHandlerFactory
    {
        private List<RewriterRule> Rules = new List<RewriterRule>();

        #region IHttpHandlerFactory 成员

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {

            string sendToUrl = url;
            string filePath = pathTranslated;

            RewriterRuleCollection Rules = RewriterConfig.GetConfig().Rules;

            foreach (RewriterRule item in Rules)
            {
                string lookFor = "^" + RewriterUtils.ResolveUrl(context.Request.ApplicationPath, item.LookFor) + "$"; 

                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

                if (re.IsMatch(url))
                {
                    sendToUrl=re.Replace(url, item.SendTo);
                    sendToUrl = RewriterUtils.ResolveUrl(context.Request.ApplicationPath, sendToUrl);

                    string sendToUrlLessQString;
                    RewriterUtils.RewriteUrl(context, sendToUrl, out sendToUrlLessQString, out filePath);
                    return PageParser.GetCompiledPageInstance(sendToUrlLessQString, filePath, context);
                }
            }
            return PageParser.GetCompiledPageInstance(url, filePath, context);
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
            
        }

        #endregion
    }
}